import { statePool } from "../compiler/state";
import { update } from "../render";
import { isObject, hasOwnProperty, isEqual } from "../share/util";
import { reactive } from "./reactive";

const get = crateGetter(),
  set = createSetter();

function crateGetter() {
  return function get(target, key, receiver) {
    const res = Reflect.get(target, key, receiver);
    console.log(`响应式获取 ${key}  ${target[key]}`);
    if (isObject(res)) {
      return reactive(res);
    }
    return res;
  };
}

function createSetter() {
  return function set(target, key, value, receiver) {
    const isKeyExit = hasOwnProperty(target, key);
    const oldVal = target[key];
    const res = Reflect.set(target, key, value, receiver);
    if (!isKeyExit) {
      console.log(`响应式新增：${key}`);
    } else if (!isEqual(value, oldVal)) {
      // console.log(`响应式修改 ${key} = ${value}`);
      update(statePool, key, value);
    }
    return res;
  };
}

const mutableHandler = {
  get,
  set,
};

export { mutableHandler };
